/**
 * @file 蚂蚁修工单列表
 * @author yangjiangming <449654337@qq.com>
 * @date 2018/11/27 10:20:40
 */

layui.define(['element', 'layer', 'searchPage', 'laydate', 'laytpl', 'formSelects', 'zmnSelect', 'zmnUtils'], function(exports) {
    var $ = layui.$;
    var layer = layui.layer;
    var laydate = layui.laydate;
    var zmnUtils = layui.zmnUtils;
    var searchPage = layui.searchPage;
    let zmnSelect = layui.zmnSelect;

    var CHAN_CLUE_DETAIL_BASE_URL = '/chan/clueDetail';
    var datePickerSelectorArray = [
        'receiveTime'
        //,'dutyTime'
    ];

    var multipleSelectNameArray = [
        'cityIdList'
    ];

    /**
     * 渲染日期选择器
     * @param selector 日期选择器的选择器或者 Dom 对象
     */
    function renderDatePicker(selector) {
        var config = {
            elem: selector,
            format: selector.indexOf('Start') !== -1 ? 'yyyy-MM-dd' : 'yyyy-MM-dd'
        };
        laydate.render(config);
    }

    /**
     * 初始化页面的所有日期组件
     */
    function initALLDatePickers() {
        $.each(datePickerSelectorArray, function(index, keyword) {
            $.each(['Start', 'End'], function(i, suffix) {
                renderDatePicker('#' + keyword + suffix);
            });
        });
    }

    /**
     * 打开对话框
     * @param {Object} config 配置
     */
    function openDialog(config) {
        var defaultConfig = {
            type: 2,
            content: '/',
            title: '',
            shade: [0.8, '#393D49'],
            area: ['80%', '80vh'],
            minWidth: '960px',
            zIndex: layer.zIndex, // 重点1
            success: function(layero) {
                parent.layer.setTop(layero); // 重点2
            }
        };

        var normalizedConfig = Object.assign({}, defaultConfig, config);

        parent.layer.open(normalizedConfig);
    }

    /**
     * 打开手机单详情页
     * @param entrustId
     */
    function openDetailDialog(orderId) {
        openDialog({
            title: '详情',
            content: zmnUtils.serializeURL(OMS_BASE_URL + '/work/detail.action', {
                orderId: orderId,
                workId: orderId
            })
        });
    }

    /**
     * 标准化搜索参数
     * @param {object} field 参数
     */
    function normalizeSearchParams(field) {
        var params = {};

        // 整理时间
        datePickerSelectorArray.forEach(function(keyword) {
            var startSelector = keyword + '.start';
            var endSelector = keyword + '.end';

            var startTime = field[startSelector];
            var endTime = field[endSelector];

            if (startTime || endTime) {
                startTime = startTime ? startTime + ' ' + '00:00:00' : '';
                endTime = endTime ? endTime + ' ' + '23:59:59' : '';

                params[keyword] = startTime + ',' + endTime;

                field[startSelector] = '';
                field[endSelector] = '';
            }
        });

        // 整理客户电话
        if (field['contactPhone'].length === 4) {
            params['contactPhoneEnd4'] = field['contactPhone'];
            field['contactPhone'] = null;
        }

        // 整理工单号
        if (field['outerId'].length === 6) {
            params['outerIdEnd6'] = field['outerId'];
            field['outerId'] = '';
        }

        // 整理操作类型、操作员
        /* if (field['operate.operateType'] || field['operate.operatorId']) {
             params['operate'] = {
                 operateType: field['operate.operateType'],
                 operatorId: field['operate.operatorId']
             };

             field['operate.operateType'] = null;
             field['operate.operatorId'] = null;
         }*/

        // 拷贝非空字段
        Object.keys(field).filter((key) => {
            if (field[key]) {
                if (multipleSelectNameArray.indexOf(key) !== -1) {
                    params[key] = field[key].split(',');
                } else {
                    params[key] = field[key];
                }
            }
        });
        console.log(params)
        return params;
    }


    searchPage.init({
        id: 'zmn-clue-detail-table',
        searchURL: CHAN_CLUE_DETAIL_BASE_URL + '/ajax/list.action',
        defaultParams: { pageSize: 15 },
        tableConfig: {
            limit: 15,
            limits: [15]
        },
        orderObj: {
            orderField: 'createTime',
            defaultOrder: 2
        },
        /*tableConfig: {
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'print']
        },*/
        init: function() {
            initALLDatePickers();
        },
        parseParams: function(dataObj) {
            let pageUrl = window.location.href;
            var params = normalizeSearchParams(dataObj.field)
            var filter_name = ''
            Object.keys(params).forEach((item, index) => {
                var fifname = $('[name^="' + item + '"]').parents('.layui-input-inline').eq($('[name^="' + item + '"]').parents('.layui-input-inline').length - 1).prev().text().split('：')[0]

                if (index != Object.keys(params).length - 1) {
                    filter_name = filter_name + fifname + '|'
                } else {
                    filter_name = filter_name + fifname
                }

            })

            try {
                if (filter_name.substring(filter_name.length - 1) == '|') {
                    filter_name = filter_name.substring(0, filter_name.length - 1)
                }
                console.log(filter_name)
                var data = {
                    employee_name: loginStaff.realName, // 内部员工姓名,
                    employee_id: loginStaff.staffId,
                    department_name: loginStaff.deptName, // 员工部门名称
                    department_id: loginStaff.deptId,
                    menu: path_name, //菜单目录路径名称
                    filter_name: filter_name,
                    tab_name: tabName || ''
                }
                webTrackingUtil('SYS_ADMIN_QUERY', pageUrl, 'click', 'SYS_ADMIN_QUERY_CLICK', data)
            } catch (error) {
                console.log(error)
            }




            return normalizeSearchParams(dataObj.field);
        },
        toolHandler: function(obj) {
            console.log(obj)
            var data = obj.data;
            switch (obj.event) {
                case 'detail':
                    openDetailDialog(data.zmnOrderId);
                    break;
                case 'apply2ZmnOrder':
                    $.post(
                        CHAN_CLUE_DETAIL_BASE_URL + '/apply2ZmnOrder.action', { clueId: data.clueId },
                        function(result) {
                            var data = result.data;
                            if (result.statusBool) {
                                if (data) {
                                    obj.update({
                                        state: data.state || 2,
                                        stateName: data.state || '生成工单-处理中',
                                        operator: data.operator,
                                        updateTime: data.updateTime
                                    });
                                }
                                zmnUtils.layui.toastSuccess("申请成功");
                            } else {
                                if (result.status == 201 && data) {
                                    // 已被别人申请的，更新页面状态
                                    if (data) {
                                        obj.update({
                                            state: data.state || 2,
                                            stateName: data.state || '生成工单-处理中',
                                            operator: data.operator,
                                            updateTime: data.updateTime
                                        });
                                    }
                                }
                                zmnUtils.layui.toastError('申请失败，请稍后再试：' + result.message);
                            }
                        });
                    break;
                case 'ignoreOrderClueDetail':
                    layer.confirm(
                        '舍弃该条线索无法生成工单，请问是否需要舍弃？', { title: '舍弃线索' },
                        function(index) {
                            $.post(
                                CHAN_CLUE_DETAIL_BASE_URL + '/ignoreOrderClueDetail.action', { clueId: data.clueId },
                                function(result) {
                                    if (result.statusBool) {
                                        zmnUtils.layui.toastSuccess("操作成功");
                                        var data = result.data;
                                        if (data) {
                                            obj.update({
                                                state: data.state || 1,
                                                stateName: data.state || '舍弃',
                                                operator: data.operator,
                                                updateTime: data.updateTime
                                            });
                                        }
                                    } else {
                                        zmnUtils.layui.toastError('操作失败：' + result.message);
                                    }
                                });
                            layer.close(index);
                        },
                        function(index) {
                            layer.close(index);
                        });
                    break;
                case 'resetState2Pending':
                    layer.confirm(
                        '确定要恢复线索么？', { title: '恢复线索' },
                        function(index) {
                            $.post(
                                CHAN_CLUE_DETAIL_BASE_URL + '/resetState2Pending.action', { clueId: data.clueId },
                                function(result) {
                                    if (result.statusBool) {
                                        zmnUtils.layui.toastSuccess("操作成功");
                                        var data = result.data;
                                        if (data) {
                                            obj.update({
                                                state: data.state || 0,
                                                stateName: data.state || '待处理',
                                                operator: data.operator,
                                                updateTime: data.updateTime
                                            });
                                        }
                                    } else {
                                        zmnUtils.layui.toastError('操作失败：' + result.message);
                                    }
                                });
                            layer.close(index);
                        },
                        function(index) {
                            layer.close(index);
                        });
                    break;
                default:
                    break;
            }
        },
    });

    zmnSelect.selectCity('cityIdList', {
        tips: "-选择城市-",
        isReload: true
    });

    exports('oms_chan_clue_detail_list');
});